package org.net5ijy.oauth2.client.base;

import static org.net5ijy.commons.http.constants.StatusCode.STATUS_OK;

import java.io.IOException;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.net5ijy.commons.http.HttpClientHttp;
import org.net5ijy.commons.http.constants.HttpHeaderNames;
import org.net5ijy.commons.http.response.HtmlResponseHolder;

/**
 * 密码模式客户端测试通用方法抽取
 *
 * @author XGF
 * @date 2020/8/16 16:49
 */
@Slf4j
public class PasswordMode {

  public static HtmlResponseHolder token(
      String tokenUrl, String username, String password, String appId, String secret, String scope)
      throws IOException {

    try (HttpClientHttp clientHttp = new HttpClientHttp()) {

      HtmlResponseHolder htmlResponseHolder = clientHttp.postHtml(
          tokenUrl,
          new HashMap<String, String>(2) {
            {
              put(HttpHeaderNames.HEADER_NAME_AUTHORIZATION,
                  "Basic " + Base64.encodeBase64String((appId + ":" + secret).getBytes()));
            }
          }, new HashMap<String, String>(1) {
            {
              put("grant_type", "password");
              put("username", username);
              put("password", password);
              put("scope", scope);
            }
          });

      if (htmlResponseHolder.getStatusCode() != STATUS_OK) {
        throw new RuntimeException("获取token失败");
      }

      return htmlResponseHolder;

    } catch (IOException e) {
      log.error(e.getMessage(), e);
      throw e;
    }
  }
}
